package com.example.chinawenddingexpo.controller;

import com.example.chinawenddingexpo.model.User;
import com.example.chinawenddingexpo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

	@Autowired
	private UserService userService;

	// 微信小程序登录
	@PostMapping("/login")
	public Map<String, Object> wxLogin(@RequestBody Map<String, String> loginData) {
		Map<String, Object> result = new HashMap<>();
		try {
			String openid = loginData.get("openid");
			String nickname = loginData.get("nickname");
			String avatarUrl = loginData.get("avatarUrl");
			Integer gender = Integer.valueOf(loginData.getOrDefault("gender", "0"));

			User user = userService.wxLogin(openid, nickname, avatarUrl, gender);
			result.put("code", 200);
			result.put("msg", "登录成功");
			result.put("data", user);
		} catch (Exception e) {
			result.put("code", 500);
			result.put("msg", "登录失败");
		}
		return result;
	}

	// 根据openid获取用户信息
	@GetMapping("/{openid}")
	public Map<String, Object> getUserInfo(@PathVariable String openid) {
		Map<String, Object> result = new HashMap<>();
		try {
			User user = userService.getUserByOpenid(openid);
			result.put("code", 200);
			result.put("msg", "success");
			result.put("data", user);
		} catch (Exception e) {
			result.put("code", 500);
			result.put("msg", "获取用户信息失败");
		}
		return result;
	}

	// 保存或更新用户信息
	@PostMapping
	public Map<String, Object> saveUser(@RequestBody User user) {
		Map<String, Object> result = new HashMap<>();
		try {
			User savedUser = userService.saveOrUpdate(user);
			result.put("code", 200);
			result.put("msg", "保存成功");
			result.put("data", savedUser);
		} catch (Exception e) {
			result.put("code", 500);
			result.put("msg", "保存失败");
		}
		return result;
	}

	// 根据用户ID获取用户信息
	@GetMapping("/id/{userId}")
	public Map<String, Object> getUserById(@PathVariable Long userId) {
		Map<String, Object> result = new HashMap<>();
		try {
			User user = userService.getUserById(userId);
			result.put("code", 200);
			result.put("msg", "success");
			result.put("data", user);
		} catch (Exception e) {
			result.put("code", 500);
			result.put("msg", "获取用户信息失败");
		}
		return result;
	}

	// 更新用户信息
	@PutMapping("/{userId}")
	public Map<String, Object> updateUser(@PathVariable Long userId, @RequestBody User user) {
		Map<String, Object> result = new HashMap<>();
		try {
			user.setId(userId);
			User updatedUser = userService.saveOrUpdate(user);
			result.put("code", 200);
			result.put("msg", "更新成功");
			result.put("data", updatedUser);
		} catch (Exception e) {
			result.put("code", 500);
			result.put("msg", "更新失败");
		}
		return result;
	}
}